package com.xuecheng.media.api;

import com.xuecheng.base.model.RestResponse;
import com.xuecheng.media.model.dto.UpLoadMediaFilesParamDto;
import com.xuecheng.media.service.impl.MediaFileServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author 冯佳鑫 又菜又爱学
 * @version 1.0
 * @DATE now()
 */
@RestController
@Api(tags = "上传大型文件接口" ,value = "上传大型文件接口" )
public class BigMediaFileController {
    @Autowired
    MediaFileServiceImpl mediaFileService;
    @PostMapping("/upload/checkfile")
    @ApiOperation("上传前检查大型文件接口")
    public RestResponse<Boolean> checkfiles(@RequestParam("fileMd5") String fileMd5){
        RestResponse<Boolean> checkfiles = mediaFileService.checkfiles(fileMd5);
        return checkfiles;
    }


    @ApiOperation(value = "分块文件上传前的检测")
    @PostMapping("/upload/checkchunk")
    public RestResponse<Boolean> checkchunk(@RequestParam("fileMd5") String fileMd5,
                                            @RequestParam("chunk") int chunk) throws Exception {
        RestResponse<Boolean> checkchunkfiles = mediaFileService.checkchunkfiles(fileMd5, chunk);
        return checkchunkfiles;
    }

    @ApiOperation(value = "分块文件上传")
    @PostMapping("/upload/uploadchunk")
    public RestResponse<Boolean> uploadChunk(@RequestParam("file") MultipartFile file,
 @RequestParam("fileMd5") String fileMd5, @RequestParam("chunk") int chunk) throws IOException {
      //创建临时文件
        File tempFile = File.createTempFile("minio", ".temp");
        //上传的文件拷贝到临时文件中
        file.transferTo(tempFile);
        //得到临时文件的路径，用于文件上传
        String absolutePath = tempFile.getAbsolutePath();
        RestResponse<Boolean> booleanRestResponse = mediaFileService.uploadChunk(fileMd5, chunk, absolutePath);
        return booleanRestResponse;
    }

    @ApiOperation(value = "合并文件")
    @PostMapping("/upload/mergechunks")
    public RestResponse mergechunks(@RequestParam("fileMd5") String fileMd5,
@RequestParam("fileName") String fileName, @RequestParam("chunkTotal") int chunkTotal) throws Exception {
        UpLoadMediaFilesParamDto paramDto = new UpLoadMediaFilesParamDto();
        Long companyId = 1232141425L;
        paramDto.setFileType("001002");
        paramDto.setFilename(fileName);
        paramDto.setTags("视频文件");
        paramDto.setRemark("");
        RestResponse<Boolean> mergechunks = mediaFileService.mergechunks(paramDto, companyId, fileMd5, chunkTotal);
        return mergechunks;
    }
}
